data = [
    { "id": 1, "key": "key1", "value":"value1", "pid": 0 },
    { "id": 2, "key": "key2", "value":"value2", "pid": 1 }, 
    { "id": 3, "key": "key3", "value":"value3", "pid": 1 }, 
    { "id": 4, "key": "key4", "value":"value4", "pid": 3 }, 
    { "id": 5, "key": "key5", "value":"value5", "pid": 4 }, 
    { "id": 6, "key": "key6", "value":"value6", "pid": 4 }
];

function toTree(pTree,tree) {
    pTree.forEach(parent => {
        parent.child = tree.filter(item => item.pid == parent.id)
        if(parent.child.length>0){
            toTree(parent.child,tree)
        }
    })
    return pTree
}

let topTree = data.filter(item => item.pid == 0);
console.log(toTree(topTree,data))